package com.itheima.service;

import com.itheima.bean.Menu;
import com.itheima.bean.Order;
import com.itheima.bean.Restaurant;
import com.itheima.bean.User;
import com.itheima.dao.OrderDaoImpl;
import com.itheima.exception.UserException;
import com.itheima.libs.TakeoutUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class OrderServiceImpl implements OrderService{
    @Override
    public Order viewOrder(String orderId) throws UserException, IOException {
        return new OrderDaoImpl().viewOrder(orderId);

    }

    @Override
    public String placeOrder(User user, String restaurantName, List<String> dishNames) throws Exception {
        final Restaurant restaurant = new RestaurantServiceImpl().browseRestaurant(restaurantName);
        List<Menu> menus = new ArrayList<>();
        // 检查每一个菜品
        for (String dish : dishNames) {
            // 从餐厅中查找这菜
            final List<Menu> collect = restaurant.getMenuList().stream()
                    .filter(menu -> dish.equals(menu.getDishName()))
                    .collect(Collectors.toList());
            if (collect.size() == 0) {
                // 没找到这个菜
                System.out.println(restaurantName + " 中没有找到 " + dish + " 这个菜，请重试.");
                return "no";
            } else {
                menus.add(collect.get(0));
            }
        }

        // 完成统计，去生成订单
        final Order order = new Order(TakeoutUtils.getOrderId(user), user, menus);
        // 订单保存
        new OrderDaoImpl().saveOrder(order);

        // 下单成功 返回订单号
        return order.getOrderId();

    }
}
